library(ggplot2)
library(dplyr)
library(tidyr)
library(ggrepel)

# Define countries to include
c_list_agg <- c(
  "East Asia & Pacific (excluding high income)", "Europe & Central Asia (excluding high income)", 
  "Latin America & Caribbean (excluding high income)", "Middle East & North Africa (excluding high income)", 
  "South Asia (excluding high income)", "Sub-Saharan Africa (excluding high income)", "LMIC"
)

# Filter dataset
total_agg <- data %>%
  filter(countrynewwb %in% c_list_agg,
         year %in% c(2011, 2014, 2017, 2021, 2024),
         group == "all") %>%
  select(countrynewwb, ts_savfor_fi_mm, year) %>%
  mutate(ts_savfor_fi_mm = ts_savfor_fi_mm * 100,
         year = as.factor(year)) %>%
  distinct()

# Define dynamic y-axis limits
y_limits <- total_agg %>%
  summarise(min_value = min(ts_savfor_fi_mm, na.rm = TRUE),
            max_value = max(ts_savfor_fi_mm, na.rm = TRUE))

y_min <- round(y_limits$min_value) - 5
y_max <- round(y_limits$max_value) + 10
if (y_max > 100) y_max <- 105
if (y_min < 0) y_min <- 0

# Nearest nice tick marks for axis
values_set <- c(0, 20, 40, 60, 80, 100)
find_nearest <- function(value, set) { set[which.min(abs(set - value))] }
nearest_max_value <- find_nearest(y_max, values_set)
nearest_min_value <- find_nearest(y_min, values_set)

# Colors
color_mapping <- c(
  "East Asia & Pacific (excluding high income)" = "#5696D0",
  "Europe & Central Asia (excluding high income)" = "#0F72BC", 
  "Latin America & Caribbean (excluding high income)" = "#B6A5CE",
  "Middle East & North Africa (excluding high income)" = "#8066AB",  
  "South Asia (excluding high income)" = "#F087B6", 
  "Sub-Saharan Africa (excluding high income)" = "#D12891",
  "LMIC" = "#878787"
)

# Line types
linetype_mapping <- c(
  "East Asia & Pacific (excluding high income)" = "solid",
  "Europe & Central Asia (excluding high income)" = "solid",
  "Latin America & Caribbean (excluding high income)" = "solid",
  "Middle East & North Africa (excluding high income)" = "solid",
  "South Asia (excluding high income)" = "solid",
  "Sub-Saharan Africa (excluding high income)" = "solid",
  "LMIC" = "dashed"
)

# Legend labels
legend_labels <- c(
  "East Asia & Pacific (excluding high income)" = "East Asia and Pacific",
  "Europe & Central Asia (excluding high income)" = "Europe and Central Asia",
  "Latin America & Caribbean (excluding high income)" = "Latin America and the Caribbean", 
  "Middle East & North Africa (excluding high income)" = "Middle East and North Africa", 
  "South Asia (excluding high income)" = "South Asia", 
  "Sub-Saharan Africa (excluding high income)" = "Sub-Saharan Africa",
  "LMIC" = "Low- and middle-income economies"
)

# Create plot
p <- ggplot(total_agg, aes(
  x = year,
  y = ts_savfor_fi_mm,
  group = countrynewwb,
  color = countrynewwb,
  linetype = countrynewwb
)) +
  geom_line(size = 1.2) +
  geom_point(
    aes(fill = countrynewwb), 
    shape = 21, 
    size = 3, 
    color = "black", 
    stroke = 1
  ) +
  scale_x_discrete(breaks = c("2011", "2014", "2017", "2021", "2024")) +
  scale_y_continuous(
    limits = c(nearest_min_value, nearest_max_value),
    breaks = seq(nearest_min_value, nearest_max_value, by = 20)
  ) +
  scale_color_manual(values = color_mapping, labels = legend_labels) +
  scale_fill_manual(values = color_mapping, labels = legend_labels) +
  scale_linetype_manual(values = linetype_mapping, labels = legend_labels) +
  guides(
    color = guide_legend(override.aes = list(linetype = linetype_mapping)),
    fill = "none"
  ) +
  theme_bw() +
  theme(
    legend.title = element_blank(),
    legend.position = "right",
    legend.direction = "vertical",
    legend.text = element_text(size = 12, family = "Nunito Sans"),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.x = element_text(size = 12, family = "Nunito Sans", color = "black"),
    axis.text.y = element_text(size = 12, family = "Nunito Sans", color = "black"),
    plot.title.position = "plot",  # Align title to the absolute left
    plot.title = element_text(
      hjust = 0, 
      size = 20, 
      family = "Nunito Sans", 
      face = "bold"
    ),
    plot.subtitle = element_text(
      hjust = 0, 
      size = 18, 
      family = "Nunito Sans"
    ),
    plot.caption = element_text(size = 12, family = "Nunito Sans", hjust = 0),
    plot.margin = margin(t = 10, r = 10, b = 30, l = 10),
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
    panel.grid.major.y = element_blank(),
    panel.grid.minor.y = element_blank(),
    panel.border = element_blank()
  ) +
  labs(
    title = "Formal savings have increased across regions between 2011 and 2024",
    subtitle = "Adults saving at a bank or similar financial institution or using a mobile money account\nin the past year (%), 2024",
    caption = "\n\nSource: Global Findex Database 2025\n\nNote: Data for 2021 and 2024 include saving using a mobile money account."
  )

# Print and save
print(p)
ggsave(
  filename = file.path(folder_path, "3.1.2.png"),
  plot = p,
  width = 10,
  height = 5,
  device = 'png',
  dpi = 120
)
